package com.rest.demo.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rest.demo.util.GsonUtil;
import com.rest.demo.util.Sha256Util;
import com.rest.demo.util.restUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Data
@Component
@Service
@Slf4j
@Configuration
@RestController
public class Dysmtl {

    @Autowired
    private RestTemplate restTemplate; //此模板需要到config下配置
    @Autowired
    private restUtil XRestUtil;


    public String access_token;//Token值


    public void postForObjectForm2() {
        System.out.println("请求地址");
        // 请求地址
        String url = "http://59.213.92.139:8181/xxxxcxjk";


        // 请求头设置,x-www-form-urlencoded格式的数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));

        //提交参数设置
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("msgId", "c3ebe4f41a8a4566896a578403f156f4");
        map.add("areaCode", "511702");
        map.add("deptCode", "51000098008989080");
        map.add("deptName", "德阳市一窗受理");
        map.add("timestamp", "1607476387");
        map.add("encryptData", "630331ae708e2c24b1333229b91f2d381637f25d36244fc086b7c1f28ef03c500f784b8dd178bbab0afd9b348e2ce6b52497f39c5fc259b83946f71e70a39611");
        // 组装请求体
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(map, headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(map);

        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(builder.toUriString(), request, JSONObject.class);
        // 发送post请求，并打印结果，以String类型接收响应结果JSON字符串
//        String result = restTemplate.postForObject(url,request,String.class);
//        ResponseEntity result = restTemplate.postForEntity(url, request, String.class);

        System.out.println(responseEntity);



//
//        if (wxTemplateVo==null||wxTemplateVo.getErrcode()!=0){
//            throw new BusinessException("模版消息发送失败，"+wxTemplateVo.getErrmsg());
//        }
//        return true;



    }


    public String ApiUrl(String Scope,String MainUrl,String authorize,String client_id,String redirect_uri) {//返回一个完整的请求地址 get
        String url = MainUrl + authorize + "?client_id=" + client_id + "&response_type=code&grant_type=authorization_code&scope=" + Scope + "&redirect_uri=" + redirect_uri;
        return url;
    }


    //Get直接获取Code
    //Scope:snsapi_base 只包括用户id,用户名
    //Scope:snsapi_baseinfo 用户基本信息
    //Scope:snsapi_userinfo 用户基本信息和敏感信息(身份证,认证资料,资料库等)
    public String GetCode(String Scope,String MainUrl,String authorize,String client_id,String redirect_uri) throws UnsupportedEncodingException {
        String url = MainUrl + authorize + "?client_id={client_id}&response_type={response_type}&grant_type={grant_type}&scope={scope}&redirect_uri={redirect_uri}";
        //组装请求参数
        Map<String, Object> parmMap = new HashMap<String, Object>();
        parmMap.put("client_id", client_id);
        parmMap.put("response_type", "code");
        parmMap.put("grant_type", "authorization_code");
        parmMap.put("scope", Scope);
        parmMap.put("redirect_uri", redirect_uri);

        String UrlInfo = URLEncoder.encode(GsonUtil.toJson(parmMap), "UTF-8");
        System.out.println(UrlInfo);
        String result = XRestUtil.get(url, parmMap);
        System.out.println(result);
        return result;
    }


//    postForEntity和postForObject区别就是前者可以返回
//    HttpStatus statusCode = responseEntity.getStatusCode();  获取整体的响应状态信息
//    int statusCodeValue = responseEntity.getStatusCodeValue(); 获取响应码值
//    HttpHeaders headers = responseEntity.getHeaders(); 获取响应头

    //Post直接传参获取Token
    public String GetToken(String Code,String MainUrl,String authorize,String client_id,String redirect_uri,String token,String client_secret) throws JSONException {
        String Token = "";
        String url = MainUrl + token + "?code=" + Code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&grant_type=authorization_code&redirect_uri=" + redirect_uri;
        System.out.println(url);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String requestJson = "{...}";
        HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
        System.out.println(headers);
        ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);//Json
        System.out.println(JSON.parseObject(result.getBody()).getString("access_token"));//获取token
        Token = JSON.parseObject(result.getBody()).getString("access_token");
        return Token;

    }


    //Post获取用户个人信息
    public JSONObject GetInfomation(String access_token,String MainUrlUser,String base) {
        String url = MainUrlUser + base + "?access_token=" + access_token;
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String requestJson = "{...}";
        HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
        System.out.println(headers);
        //        ResponseEntity<JSONObject> result = restTemplate.postForEntity(url, entity, JSONObject.class);
        //        System.out.println(JSONObject.parseObject(result.getJSONArray("roles").getString(0)).getString("authority"));//获取角色
        ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);//Json


        return JSON.parseObject(result.getBody());
    }


    //Post获取用户个人信息
    public JSONObject GetUserInfomation(String access_token,String MainUrlUser,String userinfo) {


        String url = MainUrlUser + userinfo + "?access_token=" + access_token;
        System.out.println(url);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String requestJson = "{...}";
        HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
        System.out.println(headers);
        ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);//Json
        return JSON.parseObject(result.getBody());
    }

    //带请求头的head
    public JSONObject GetHealthInfo(String xm, String zjhm) {
        String token = "bA1Kp3ycrQVNEUUim5XrrP7cusHDKIpr";
//        String url = API_ROOT + "/NHC-COVID19-interface/gov-data/health-info?xm=" + xm + "&zjhm=" + zjhm;
        String url = "https://rio.scdsjzx.cn/ebus/net2/gjwjwfwdl/NHC-COVID19-interface/gov-data/health-info?xm=" + xm + "&zjhm=" + zjhm;

        RestTemplate restTemplate = new RestTemplate();
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
        String nonce = String.valueOf(System.currentTimeMillis());
        String sign = Sha256Util.getSHA256(timestamp + token + nonce + timestamp);
        System.err.println(timestamp);
        System.err.println(nonce);
        System.err.println(sign);

        HttpHeaders headers = new HttpHeaders();
        headers.add("x-tif-paasid", "gjwjwfwdl");
        headers.add("x-tif-timestamp", timestamp);
        headers.add("x-tif-nonce", nonce);
        headers.add("x-tif-signature", sign);
        System.err.println(url);

        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(null, headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);

        Object result = restTemplate.exchange(builder.build().toString(), HttpMethod.GET, request, Object.class).getBody();
        String data = JSONObject.toJSONString(result);
        System.out.println(data);
        JSONObject UserHealth = JSONObject.parseObject(data).getJSONObject("data");//获取健康信息数据

        //System.out.println(hh.getJSONObject("data").getJSONObject("person").getString("desensitizeCardId"));
        return UserHealth;

    }


}

